<?php
header("Content-type: text/html;charset=utf-8");
date_default_timezone_set('Asia/Shanghai');
session_start();
/*
$db = new mysqli('localhost','root','root','think_b2c_db');
$db->set_charset("utf8");
*/
$conn=mysql_connect("localhost","root","root");
mysql_select_db("nianhui", $conn);
mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $conn);

//数据列表
function db_fetch_arrays($sql) 	{
	global $conn;
	$result = mysql_query($sql, $conn);
	$i = 0;
	$_res = array();
	while(@$res = mysql_fetch_array($result,MYSQL_ASSOC)) {
		foreach ($res as $key => $value){
			$_res[$i][$key] = $value;//直接转义
		}
		$i++;
	}
	return $_res;
}
//单条数据
function db_fetch_array($sql) {
	global $conn;
	$result = mysql_query($sql, $conn);
	$res = mysql_fetch_array($result,MYSQL_ASSOC);
	$_res = "";
	if (is_array($res)){
		foreach ($res as $key => $value){
			$_res[$key] =$value;
		}
	}
	$query = $_res;
	return $query;
}
//总数据
function db_count(){
	global $conn;
	$sql = "SELECT * FROM `think_user_book`";
	$result =  mysql_query($sql, $conn);
	$_SESSION['count'] = mysql_num_rows($result);
	return $_SESSION['count'];
}
//查询
function db_query($sql){
	global $conn;
	$count = db_count($sql);
	return ($count > 0 )?true:false;
}
//获取用户
function getUser($num=200){
	if( isset($_SESSION['user']) && !empty($_SESSION['user']) ){
		return $_SESSION['user'];
	}
	$list_array = getList($num);
	$list = array();
	foreach($list_array as $k => $v ){
		$sql = "SELECT name,identity FROM `think_user_book` where id= {$v}";
		$data = db_fetch_array($sql);
		$identity = substr($data['identity'],-4);
		$name = $data['name']."({$identity})";
		$list[$k] = $name;
	}
	$_SESSION['user'] = $list;
	return $_SESSION['user'];
}
//获取列表
function getList($num = 200){
	if( isset($_SESSION['list']) && !empty($_SESSION['list']) ){
		return $_SESSION['list'];
	}
	$data = array();
	while(true){
		$data[] = getID();
		$data = array_flip(array_flip($data));
		$count = count($data);
		if( $count > $num ) break;
	}
	$i=0;
	$list = array();
	foreach($data as $k => $v ){
		$list[$i] = $v;
		$i++;
	}
	$_SESSION['list'] = $list;
	return $_SESSION['list'];
}
//获取随机ID
function getID(){
	if( isset($_SESSION['count']) && !empty($_SESSION['count']) ){
		$count = $_SESSION['count'];
	}else{
		$count = db_count();
	}
	return rand(1,intval($count));
}
